package com.itheima.attendance.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.attendance.mapper.AttendanceConfigMapper;
import com.itheima.attendance.mapper.AttendanceMapper;
import com.itheima.attendance.mapper.CompanySettingsMapper;
import com.itheima.attendance.mapper.UserMapper;
import com.itheima.attendance.pojo.Attendance;
import com.itheima.attendance.pojo.AttendanceConfig;
import com.itheima.attendance.pojo.CompanySettings;
import com.itheima.attendance.pojo.User;
import com.itheima.attendance.pojo.bo.AtteItemBO;
import com.itheima.attendance.pojo.vo.AtteUploadVo;
import com.itheima.attendance.service.AttenService;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.ResultCode;
import com.itheima.common.exception.IhrmException;
import com.itheima.common.utils.DateUtils;
import com.itheima.common.utils.IdWorker;
import com.itheima.common.utils.ImportExcelUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/12/12 12:54
 */
@Service
@Transactional
@SuppressWarnings(value = "all")
public class AttenServiceImpl implements AttenService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AttendanceConfigMapper attendanceConfigMapper;

    @Autowired
    private AttendanceMapper attendanceMapper;

    @Autowired
    private CompanySettingsMapper companySettingsMapper;

    @Value("${atte.holidays}")
    private String holidays;

    @Value("${atte.workingDays}")
    private String workingDays;

    /**
     * 导入考勤数据
     */
    @Override
    public void importAttenDate(MultipartFile file, String companyId) throws Exception {
        List<AtteUploadVo> atteUploadVoList=null;
        if(file!=null){
            atteUploadVoList = new ImportExcelUtils<AtteUploadVo>(AtteUploadVo.class).readExcel(file.getInputStream(), 1, 0);
        }
        if(!CollectionUtils.isEmpty(atteUploadVoList)){
            for (AtteUploadVo atteUploadVo : atteUploadVoList) {
                QueryWrapper<User> queryWrapper=new QueryWrapper<User>();
                queryWrapper.eq("mobile",atteUploadVo.getMobile());
                User user = userMapper.selectOne(queryWrapper);
                if(user==null){
                    throw new IhrmException(ResultCode.USERNOTFOUND);
                }
                Attendance attendance=new Attendance(atteUploadVo,user);
                //考情状态 1正常  3迟到  4早退 23休息
                if(this.holidays.contains(atteUploadVo.getAtteDate())){
                    //国家法定假期
                    attendance.setAdtStatu(23);
                }else if(DateUtils.isWeekend(atteUploadVo.getAtteDate()) && (!(this.workingDays.contains(atteUploadVo.getAtteDate())))){
                    //周末除了工作日的
                    attendance.setAdtStatu(23);
                }else {
                    //根据当前公司，部门查询考勤的时间点（上下班时间）
                    QueryWrapper<AttendanceConfig> query=new QueryWrapper<AttendanceConfig>();
                    query.and(i->i.eq("company_id",companyId).eq("department_id",attendance.getDepartmentId()));
                    AttendanceConfig attendanceConfig = attendanceConfigMapper.selectOne(query);
                    if(!DateUtils.comparingDate(attendanceConfig.getAfternoonStartTime(),atteUploadVo.getInTime())){
                        //迟到
                        attendance.setAdtStatu(3);
                    }else if(DateUtils.comparingDate(attendanceConfig.getAfternoonEndTime(),atteUploadVo.getOutTime())){
                        //早退
                        attendance.setAdtStatu(4);
                    }else {
                        //正常
                        attendance.setAdtStatu(1);
                    }
                }
                attendance.setDay(atteUploadVo.getAtteDate());
                //根据userId,departmentId,companyId查询是否有过考勤记录
                QueryWrapper<Attendance> attendanceQuery=new QueryWrapper<Attendance>();
                attendanceQuery.and(j->j.eq("user_id",attendance.getUserId()).eq("user_id",user.getId()).eq("day",atteUploadVo.getAtteDate()));
                Attendance ac = attendanceMapper.selectOne(attendanceQuery);
                if(ac==null){
                    attendance.setId(String.valueOf(idWorker.nextId()));
                    //新增
                    attendanceMapper.insert(attendance);
                }else {
                    //修改
                    attendanceMapper.update(attendance,attendanceQuery);
                }
            }
        }else{
            throw new RuntimeException();
        }
    }

    /**
     * 根据企业id查询考勤月
     */
    @Override
    public List<String> findCompanySetttinsList(String comanyId) {
        QueryWrapper<CompanySettings> queryWrapper=new QueryWrapper<CompanySettings>();
        queryWrapper.and(i->i.eq("company_id",comanyId).eq("is_settings",1));
        List<CompanySettings> companySettingsList = companySettingsMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(companySettingsList)){
            return null;
        }
        return companySettingsList.stream().map(CompanySettings::getDataMonth).collect(Collectors.toList());
    }

    /**
     * 查询考勤数据列表
     */
    @Override
    public Map<String, Object> findAttenDateList(Integer page, Integer pageSize, String dataMonth,String companyId) throws ParseException {
        Map<String,Object> resultMap=new HashMap<String,Object>(0);
        PageHelper.startPage(page,pageSize);
        //根据companyId查询用户
        QueryWrapper<User> userQuery=new QueryWrapper<User>();
        userQuery.eq("company_id",companyId);
        List<User> userList = userMapper.selectList(userQuery);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        }
        //根据dateMonth获取到当前月份的每一天
        List<AtteItemBO> atteItemBOList=new ArrayList<AtteItemBO>();
        for (User user : userList) {
            AtteItemBO bo=new AtteItemBO();
            BeanUtils.copyProperties(user,bo);
            String[] daysByYearMonth = DateUtils.getDaysByYearMonth(dataMonth);
            List<Attendance> attendRecordList=new ArrayList<Attendance>();
            for (String s : daysByYearMonth) {
                //根据日期和userId查询考勤记录
                QueryWrapper<Attendance> attendanceQuery=new QueryWrapper<Attendance>();
                attendanceQuery.and(j->j.eq("user_id",user.getId()).eq("day",s));
                Attendance attendance = attendanceMapper.selectOne(attendanceQuery);
                if(attendance==null){
                    attendance=new Attendance();
                    attendance.setAdtStatu(2);
                    attendance.setUserId(user.getId());
                    attendance.setDay(s);
                }
                attendRecordList.add(attendance);
            }
            bo.setAttendanceRecord(attendRecordList);
            atteItemBOList.add(bo);
        }
        PageInfo<AtteItemBO> pageInfo=new PageInfo<AtteItemBO>(atteItemBOList);
        PageResult<AtteItemBO> pageResult=new PageResult<AtteItemBO>(pageInfo.getTotal(),pageInfo.getList());
        //封装返回数据
        resultMap.put("data",pageResult);
        resultMap.put("tobeTaskCount",0);
        resultMap.put("monthOfReport",Integer.parseInt(dataMonth.substring(4)));
        return resultMap;
    }

    /**
     * 考勤数据修改
     */
    @Override
    public void editAttenDate(Attendance attendance) {
        QueryWrapper<Attendance> attendanceQuery=new QueryWrapper<Attendance>();
        attendanceQuery.and(i->i.eq("company_id",attendance.getCompanyId()).eq("user_id",attendance.getUserId()).eq("day",attendance.getDay()));
        Attendance atten = attendanceMapper.selectOne(attendanceQuery);
        if(atten==null){
            attendance.setId(String.valueOf(idWorker.nextId()));
            attendanceMapper.insert(attendance);
            return;
        }
        attendanceMapper.update(attendance,attendanceQuery);
    }
}
